package main

import(
	"strconv"
	"fmt"
)

type Room struct{
	C chan string
	id int
	list map[int]int
}

var RoomList = make(map[int]Room)

type RoomHandler struct{
	flag 	int // 0 进入 	1退出
	uid 	int		// 操作者
	oldId 	int	// 旧房间号
	newId	int	//新房间号	
}
var RoomChan = make(chan RoomHandler)

func RoomJoin(){
	for{
		select{
		case  handler := <- RoomChan:
			// 退出，并清理没有人房间
				fmt.Println("============", handler)
			if  room, ok := RoomList[handler.oldId]; ok{
				delete(room.list, handler.oldId)
				RoomList[handler.oldId] = room
				room.checkClearRoom()
				room.QuitCast(handler.uid)
			}
			//进入
			if handler.flag == 0 && handler.newId == 0{
				client := clientList[handler.uid]
				ids := make([]int, 1)
				ids[0] = handler.oldId
				client.SysHandler(2, ids, "")
			}else if handler.flag == 0{
				if  nroom, nok := RoomList[handler.newId]; nok{
				fmt.Println("===========22=", handler)
					
					nroom.list[handler.uid] = handler.uid;
					RoomList[handler.newId] = nroom
					nroom.JoinCast(handler.uid)
					
				}else{
				fmt.Println("=========33===", handler)
					nroom := Room{C:make(chan string), id:handler.newId, list:make(map[int]int)}
					nroom.list[handler.uid] = handler.uid
					RoomList[handler.newId] = nroom
					go nroom.start()
				fmt.Println("=========44===", RoomList)
					nroom.OpenCast(handler.uid)
				}
			}
				
		}
	}
}

func (this *Room) start(){
	for{
		select{
		case msg:= <- this.C:
			this.CastAll(msg)
			
		}
	}
}
func (this *Room) CastAll(msg string){
	for _ ,data := range this.list{
		fmt.Println("=========55===", data)
		if client, ok := clientList[data]; ok{
			client.C <- msg
		}
	}
}

func (this *Room)checkClearRoom(){
	if len(this.list) == 0{
		delete(RoomList, this.id)
	}
}

func (this *Room) JoinCast(uid int){
	client := clientList[uid]
	ids := make([]int, 1)
	ids[0] = this.id
	client.SysHandler(1, ids, "")
	this.CastAll("【房间" + strconv.Itoa(this.id) + "】欢迎[" + client.name + "]加入")
}
func (this *Room) QuitCast(uid int){
	client := clientList[uid]
	ids := make([]int, 1)
	ids[0] = this.id
	client.SysHandler(0, ids, "")
	this.CastAll("【房间" + strconv.Itoa(this.id) + "】[" + client.name + "]退出")
}
func (this *Room) OpenCast(uid int){
	client := clientList[uid]
	ids := make([]int, 1)
	ids[0] = this.id
	client.SysHandler(1, ids, "")
	this.CastAll("【房间" + strconv.Itoa(this.id) + "】创建成功")
}